﻿import 'package:get/get.dart';
import '../routes.dart';

/// 目标设置选项模型
class GoalOption {
  final String value;
  final String description;
  final dynamic data; // 存储实际的数值或配置

  const GoalOption({
    required this.value,
    this.description = '',
    this.data,
  });
}

/// 目标设置控制器
class GoalSettingLogic extends GetxController {
  /// 当前选中的标签索引 (0:里程, 1:时间, 2:配速, 3:卡路里)
  RxInt selectedTabIndex = 0.obs;

  /// 当前选中的里程目标
  RxString selectedDistance = '3.0'.obs;

  /// 当前选中的时间目标
  RxString selectedTime = '00:20'.obs;

  /// 当前选中的配速目标
  RxString selectedPace = '08\'00\'\''.obs;

  /// 当前选中的卡路里目标
  RxString selectedCalories = '300'.obs;

  /// 里程预设选项
  List<GoalOption> get distanceOptions => [
        const GoalOption(value: '3.0 千米', data: 3.0),
        const GoalOption(value: '5.0 千米', data: 5.0),
        const GoalOption(value: '10.0 千米', data: 10.0),
        const GoalOption(value: '15.0 千米', data: 15.0),
        const GoalOption(
            value: '21.0975 千米', description: '半程马拉松', data: 21.0975),
        const GoalOption(value: '42.195 千米', description: '马拉松', data: 42.195),
      ];

  /// 时间预设选项
  List<GoalOption> get timeOptions => [
        const GoalOption(value: '10 分钟', data: 10),
        const GoalOption(value: '20 分钟', data: 20),
        const GoalOption(value: '30 分钟', data: 30),
        const GoalOption(value: '60 分钟', data: 60),
        const GoalOption(value: '90 分钟', data: 90),
        const GoalOption(value: '120 分钟', data: 120),
      ];

  /// 配速预设选项
  List<GoalOption> get paceOptions => [
        const GoalOption(value: '10\'00\'\'', data: '10:00'),
        const GoalOption(value: '08\'00\'\'', data: '08:00'),
        const GoalOption(value: '06\'00\'\'', data: '06:00'),
        const GoalOption(value: '05\'00\'\'', data: '05:00'),
        const GoalOption(value: '04\'00\'\'', data: '04:00'),
        const GoalOption(value: '03\'00\'\'', data: '03:00'),
      ];

  /// 卡路里预设选项
  List<GoalOption> get caloriesOptions => [
        const GoalOption(value: '150 千卡', description: '轻松', data: 150),
        const GoalOption(value: '300 千卡', description: '普通', data: 300),
        const GoalOption(value: '350 千卡', description: '适量运动', data: 350),
        const GoalOption(value: '400 千卡', description: '积极', data: 400),
        const GoalOption(value: '500 千卡', description: '激烈', data: 500),
        const GoalOption(value: '700 千卡', description: '极限运动', data: 700),
      ];

  /// 选择标签
  void selectTab(int index) {
    selectedTabIndex.value = index;
  }

  /// 获取当前显示的值
  String getCurrentValue() {
    switch (selectedTabIndex.value) {
      case 0: // 里程
        return selectedDistance.value;
      case 1: // 时间
        return selectedTime.value;
      case 2: // 配速
        return selectedPace.value;
      case 3: // 卡路里
        return selectedCalories.value;
      default:
        return '';
    }
  }

  /// 获取当前单位
  String getCurrentUnit() {
    switch (selectedTabIndex.value) {
      case 0: // 里程
        return '千米';
      case 1: // 时间
        return '小时：分钟';
      case 2: // 配速
        return '分钟/千米';
      case 3: // 卡路里
        return '千卡';
      default:
        return '';
    }
  }

  /// 获取当前标签的预设选项
  List<GoalOption> getPresetOptions() {
    switch (selectedTabIndex.value) {
      case 0: // 里程
        return distanceOptions;
      case 1: // 时间
        return timeOptions;
      case 2: // 配速
        return paceOptions;
      case 3: // 卡路里
        return caloriesOptions;
      default:
        return [];
    }
  }

  /// 判断选项是否被选中
  bool isOptionSelected(GoalOption option) {
    bool selected = false;

    switch (selectedTabIndex.value) {
      case 0: // 里程
        final distance = option.data as double;
        selected = distance.toString() == selectedDistance.value;
        break;
      case 1: // 时间
        final timeValue = option.data as int;
        final hours = timeValue ~/ 60;
        final mins = timeValue % 60;
        final timeStr =
            '${hours.toString().padLeft(2, '0')}:${mins.toString().padLeft(2, '0')}';
        selected = timeStr == selectedTime.value;
        break;
      case 2: // 配速
        selected = option.value == selectedPace.value;
        break;
      case 3: // 卡路里
        final calories = option.data as int;
        selected = calories.toString() == selectedCalories.value;
        break;
      default:
        selected = false;
    }

    return selected;
  }

  /// 选择选项
  void selectOption(GoalOption option) {
    switch (selectedTabIndex.value) {
      case 0: // 里程
        final distance = option.data as double;
        selectedDistance.value = distance.toString();
        break;
      case 1: // 时间
        final minutes = option.data as int;
        final hours = minutes ~/ 60;
        final mins = minutes % 60;
        selectedTime.value =
            '${hours.toString().padLeft(2, '0')}:${mins.toString().padLeft(2, '0')}';
        break;
      case 2: // 配速
        selectedPace.value = option.value;
        break;
      case 3: // 卡路里
        final calories = option.data as int;
        selectedCalories.value = calories.toString();
        break;
    }
  }

  /// 确认设置
  void confirmSetting() {
    // 直接跳转到倒计时页面
    _goToCountdownPage();
  }

  /// 跳转到倒计时页面
  void _goToCountdownPage() {
    // 获取运动类型信息
    final exerciseName = _getExerciseName();
    final targetInfo = _getTargetInfoText();

    Get.offAllNamed(ExerciseRoutes.countdown, arguments: {
      'exerciseName': exerciseName,
      'targetInfo': targetInfo,
    });
  }

  /// 获取运动类型名称
  String _getExerciseName() {
    // 这里可以从传入参数获取，或者使用默认值
    final arguments = Get.arguments as Map<String, dynamic>?;
    return arguments?['exerciseName'] ?? 'GPS散步';
  }

  /// 获取目标信息文本
  String _getTargetInfoText() {
    switch (selectedTabIndex.value) {
      case 0: // 里程
        return '${selectedDistance.value}千米';
      case 1: // 时间
        return selectedTime.value;
      case 2: // 配速
        return '配速 ${selectedPace.value}';
      case 3: // 卡路里
        return '${selectedCalories.value}千卡';
      default:
        return '自由训练';
    }
  }

  @override
  void onInit() {
    super.onInit();

    // 如果有传入的参数，设置默认值
    final arguments = Get.arguments as Map<String, dynamic>?;
    if (arguments != null) {
      if (arguments['distance'] != null) {
        selectedDistance.value = arguments['distance'].toString();
      }
      if (arguments['time'] != null) {
        selectedTime.value = arguments['time'].toString();
      }
      if (arguments['pace'] != null) {
        selectedPace.value = arguments['pace'].toString();
      }
      if (arguments['calories'] != null) {
        selectedCalories.value = arguments['calories'].toString();
      }

      // 设置默认选中的标签
      if (arguments['defaultTab'] != null) {
        selectedTabIndex.value = arguments['defaultTab'] as int;
      }
    }

    // 确保初始值与预设选项匹配
    _ensureValidInitialValues();
  }

  /// 确保初始值与预设选项匹配
  void _ensureValidInitialValues() {
    // 如果当前里程值不在预设选项中，设置为默认的3.0
    bool distanceMatch = distanceOptions.any((option) =>
        (option.data as double).toString() == selectedDistance.value);
    if (!distanceMatch) {
      selectedDistance.value = '3.0';
    }

    // 如果当前时间值不在预设选项中，设置为默认的20分钟
    bool timeMatch = timeOptions.any((option) {
      final timeValue = option.data as int;
      final hours = timeValue ~/ 60;
      final mins = timeValue % 60;
      final timeStr =
          '${hours.toString().padLeft(2, '0')}:${mins.toString().padLeft(2, '0')}';
      return timeStr == selectedTime.value;
    });
    if (!timeMatch) {
      selectedTime.value = '00:20';
    }

    // 如果当前配速值不在预设选项中，设置为默认值
    bool paceMatch =
        paceOptions.any((option) => option.value == selectedPace.value);
    if (!paceMatch) {
      selectedPace.value = '08\'00\'\'';
    }

    // 如果当前卡路里值不在预设选项中，设置为默认的300
    bool caloriesMatch = caloriesOptions.any(
        (option) => (option.data as int).toString() == selectedCalories.value);
    if (!caloriesMatch) {
      selectedCalories.value = '300';
    }
  }
}
